/* 
 * File:   FileParser.h
 * Author: RedEyedKiller
 *
 * Created on 4 Μάϊος 2010, 12:08 πμ
 */

#ifndef _FILEPARSER_H
#define	_FILEPARSER_H

#include <list>
#include <vector>
#include "tinyxml.h"
#include "../TileProperties.h"
#include "../global_script_functions.h"
#include "AbstractParser.h"

class LevelMap;

namespace FileParser
{

struct PointHandler
{
    virtual void operator()(const Math::Vector2I& point, const std::string& type, const std::string& name, TiXML::TiXmlElement* xPoint = NULL)const = 0;
};

struct SpawnPointHandler : public PointHandler
{

    virtual void operator()(const Math::Vector2I& point, const std::string& type, const std::string& name, TiXML::TiXmlElement* xPoint = NULL) const
    {
        ParseProperties(xPoint->FirstChildElement("properties"), SpawnEntity(type, name, point.GetX(), point.GetY(), layer));
    }

    /**
     * The name of the rendering layer the entities will belong
     */
    std::string layer;

private:
    void ParseProperties(TiXML::TiXmlElement* xProps, EntitySystem::Entity * entity) const;
};

struct FreeTilePointHandler : public PointHandler
{
    virtual void operator()(const Math::Vector2I& point, const std::string& type, const std::string& name, TiXML::TiXmlElement* xPoint = NULL) const;

    /**
     * The name of the rendering layer the entities will belong
     */
    std::string layer;
    
    LevelMap* cacheMap;

private:
    void ParseProperties(TiXML::TiXmlElement* xProps, EntitySystem::Entity * entity) const;/*not implemented/not needed yet*/
};

/**
 * Class that handles map reading from txm files.
 * @param name - the name of the file.
 * @param playlist - a list to place audio playlist.
 */
class LevelParser : public AbstractParser
{
public:
    LevelParser(const char* name, std::list<std::string>* playlist = NULL);
    virtual ~LevelParser();
    bool ParseLevel(LevelMap* cacheMap, TileProperties* prop);
protected:
    bool ParseMapProperties(TiXML::TiXmlElement* xProp, LevelMap* cacheMap);
    bool ParseTileset(TiXML::TiXmlElement* xTileset, LevelMap* cacheMap, TileProperties* prop);
    bool ParseLayers(TiXML::TiXmlElement* xLayer, LevelMap* cacheMap);
    bool ParseObjectLayer(TiXML::TiXmlElement* xOLayer, LevelMap* cacheMap);
    bool ParseRenderingLayer(TiXML::TiXmlElement* xOLayer);
    bool ParsePoint(TiXML::TiXmlElement* xOLayer, const PointHandler& handler);
    bool ParseCSV(std::string& data, LevelMap* cacheMap);
    bool ParseTiles(TiXML::TiXmlElement* xTile, LevelMap* cacheMap, TileProperties* prop);
    void RegisterTileProperties(LevelMap* cacheMap);
private:
    std::list<std::string>* playlist;
    std::string fname;
    std::vector<std::pair<unsigned int, unsigned long> > tiles;
};

};

#endif	/* _FILEPARSER_H */

